package LinkDatabase;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

public class UserDao {
		static QueryRunner runner=new QueryRunner(JDBCUtil.getDataSource());
		private static char[] hexArr = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
	public int queryUser(String name,String password) {
		if(name.length()==0||password.length()==0) {
			return 0;
		}
		String secret=encryPassword(password);
		String sqlString="select  *from User where userName=? and userPassword=?";
	
		try {
			if( runner.query(sqlString,new BeanHandler<>(User.class), name,secret)!=null) {
				System.out.println();
				return 1;
			}
		} catch (SQLException e) {
		throw new RuntimeException("查询失败", e);
		}
		return 0;
	}

	public List<User> queryAll() {
		String sqlString="select *from User";
		try {
			return runner.query(sqlString, new BeanListHandler<>(User.class));
		} catch (SQLException e) {
			throw new RuntimeException("查询失败", e);
		}
	}
	public int updateUser(User old_user,User new_user) {
		// TODO Auto-generated method stub
			String sql="update User set userName=?,userPassword=? where userName=?";
			String secret=encryPassword(new_user.getUserPassword());
			try {
				return runner.update(sql, new_user.getUserName(),secret,old_user.getUserName());
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new RuntimeException("修改失败", e);
			}
	}
	
	//添加成绩
		public int addScore(String username,int score) {
			String sql="insert into userScore values(?,?)";
			try {
				return runner.update(sql, username,score);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				throw new RuntimeException("插入成绩失败", e); 
			}
		}
		
		//返回成绩
		public Map< String, Integer> scores(){
			String sqlString="select * from userScore";
			List<userScore> userScores=new ArrayList<userScore>();
			Map<String, Integer> map=new HashMap<String, Integer>();
			try {
				userScores=runner.query(sqlString, new BeanListHandler<>(userScore.class));
					for(userScore us:userScores) {
					map.put(us.getUserName(), us.getScore());
				}
				return map;
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				throw new RuntimeException("查找失败", e);
			}
			
		}
	
	public int addUser(User user) {
		if(user.getUserName().length()==0||user.getUserPassword().length()==0) {
			return 0;
		}
		List<User> users=queryAll();
		for(User user2:users) {
			if(user2.getUserName().equals(user.getUserName())) {
				return 0;
			}
		}
		String sqlString="insert into User values(?,?,?,?)";
		try {
			String secret=encryPassword(user.getUserPassword());
			return runner.update(sqlString, user.getUserName(),secret,user.getUserFindQuestion(),user.getUserFindAnswer());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}
	
	public User FindPassword(String username) {
		String sqlString="select *from User  where userName=?";
		try {
			return runner.query(sqlString,new BeanHandler<>(User.class), username);
		} catch (SQLException e) {
			 throw new RuntimeException("失败", e);
		}
		
	}
	
	
	public String  encryPassword(String password) {
		
		
        
        try {
            //通过 JAVA 的 Security 包，得到 MD5 表示方式 的字节数组
            MessageDigest instance = MessageDigest.getInstance("MD5");
            
            //此字节数据是 128 位的长整数，即是 16 个字节表示的数据
            byte[] digest = instance.digest(password.getBytes());
            
            
            //转换为 16 进制后的字节数组
            char[] hexByte = new char[16*2];
            //记录 当前计算后的字节在 十六进制字节数组中的位置
            int k = 0;
            
            //循环遍历 MD5 中的每个字节，并将每个字节改成对应的 16 进制进行表示
            for (int i = 0; i < 16; i++) {
                
                //计算当前字节的高四位所对应的十六进制数
                hexByte[k++] = hexArr[digest[i] >>> 4 & 0xf];
                
                //计算当前字节的低四位所对应的十六进制数
                hexByte[k++] = hexArr[digest[i] & 0xf];
            }
            //将转化后的字符数组转为 String 类型
            String hexString = new String(hexByte);
            System.out.println(hexString);
            return hexString;
            
        } catch (NoSuchAlgorithmException e) {
         throw new RuntimeException("加密失败", e);
        }
	}
	public static void main(String[] args) {
//测试代码
//		UserDao userDao=new UserDao();
//		String nameString="陈帅逼";
//		String passString="123456";
//		User user=new User();
//		user=userDao.FindPassword(nameString);
//		Scanner scanner=new Scanner(System.in);
//		System.out.println(user.getUserFindQuestion());
//		System.out.println("请输入你的问题答案");
//		String answerString=scanner.next();
//		if(user.getUserFindAnswer().equals(answerString)) {
//			//覆盖掉原来的密码；
//			System.out.println("输入新密码");
//			String newPassString=scanner.next();
//		}
//		else {
//			
//			System.out.println("问题验证失败");
//		}
		
	}
}
